package com.lollipop.programming.thread.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        // 创建CountDownLatch，初始计数为3
        CountDownLatch latch = new CountDownLatch(3);

        ExecutorService executor = Executors.newFixedThreadPool(3);

        // 创建3个任务
        for (int i = 1; i <= 3; i++) {
            final int taskId = i;
            executor.submit(() -> {
                try {
                    log.info("任务{}开始执行", taskId);
                    // 模拟任务执行时间
                    Thread.sleep(1000 * taskId);
                    log.info("任务{}执行完成", taskId);
                } catch (InterruptedException e) {
                    log.error("任务{}执行失败:{}", taskId, e.getMessage());
                } finally {
                    // 计数减1
                    latch.countDown();
                }
            });
        }

        log.info("主线程等待所有任务完成...");
        // 主线程等待所有任务完成
        latch.await();
        log.info("所有任务已完成，主线程继续执行");

        executor.shutdown();
    }
}